/*
 * @lc app=leetcode.cn id=655 lang=typescript
 *
 * [655] 输出二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function printTree(root: TreeNode | null): string[][] {
  const calcDepth = (node: TreeNode | null): number => {
    if (node === null) return 0;
    return Math.max(calcDepth(node.left), calcDepth(node.right)) + 1;
  };

  const dfs = (
    ans: string[][],
    node: TreeNode | null,
    depth: number,
    r: number,
    c: number
  ): void => {
    ans[r][c] = node.val.toString();
    if (node.left) {
      dfs(ans, node.left, depth, r + 1, c - (1 << (depth - r - 1)));
    }
    if (node.right) {
      dfs(ans, node.right, depth, r + 1, c + (1 << (depth - r - 1)));
    }
  };

  // 高度从0开始
  const depth = calcDepth(root) - 1;
  const m = depth + 1;
  const n = (1 << m) - 1;
  const ans = new Array(m).fill(0).map(() => new Array(n).fill(''));
  dfs(ans, root, depth, 0, (n - 1) >> 1);

  return ans;
}
// @lc code=end
